/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.accessor.properties;

import cc.aileron.dxo.NumberDxo;
import cc.aileron.dxo.StringToNumberDxo;

import com.google.inject.Inject;

/**
 * @author aileron
 * 
 */
public class NumberConvertorImpl implements NumberConvertor
{
    @Override
    public Object convertValue(final Class<?> type, final Object value)
    {
        if (type == Boolean.TYPE || type == Boolean.class)
        {
            if (value == null)
            {
                return false;
            }
            if (Number.class.isAssignableFrom(value.getClass()))
            {
                return ((Number) value).intValue() != 0;
            }
            return true;
        }

        if (value == null && type.isPrimitive())
        {
            return 0;
        }

        if (value instanceof Number)
        {
            return numberDxo.convert((Number) value, type);
        }

        if (value instanceof String && type.isPrimitive())
        {
            return stringDxo.convert((String) value, type);
        }

        if (value instanceof String && Number.class.isAssignableFrom(type))
        {
            return stringDxo.convert((String) value, type);
        }

        return value;
    }

    /**
     * @param numberDxo
     * @param stringDxo
     */
    @Inject
    public NumberConvertorImpl(final NumberDxo numberDxo,
            final StringToNumberDxo stringDxo)
    {
        this.numberDxo = numberDxo;
        this.stringDxo = stringDxo;
    }

    private final NumberDxo numberDxo;

    private final StringToNumberDxo stringDxo;
}
